﻿using System;
using NHibernate;

namespace HinduShop.DbClassLib
{
    public static class UnitOfWork
    {
        public static IUnitOfWork Current
        {
            get
            {
                if (innerUnitOfWork == null)
                    throw new System.InvalidOperationException("U're not in a UOW");
                return innerUnitOfWork;
            }
        }

        private static IUnitOfWorkFactory unitOfWorkFactory;

        public static IUnitOfWorkFactory UnitOfWorkFactory
        {
            get { return (unitOfWorkFactory ?? (unitOfWorkFactory = new UnitOfWorkFactory())); }
        }

        private static IUnitOfWork innerUnitOfWork;

        public static IUnitOfWork Start()
        {
            if (innerUnitOfWork != null)
            {
                throw new InvalidOperationException("You can not start more then one unit of work at the same time");
            }
            innerUnitOfWork = UnitOfWorkFactory.Create();

            return innerUnitOfWork;
        }

        public static bool IsStarted
        {
            get { return innerUnitOfWork != null; }
            
        }

        public static ISession CurrentSession
        {
            get { return unitOfWorkFactory.CurrentSession; }
            internal set { unitOfWorkFactory.CurrentSession = value; }
        }
    }
}